<template>
  <div class="doctor-container">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-card shadow="hover">
        <el-row :gutter="20" align="middle">
          <el-col :span="6">
            <el-input
                v-model="doctorName"
                placeholder="请输入医生姓名"
                clearable
                @clear="paging(1)"
                @keyup.enter="paging(1)">
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="2">
            <el-button
                type="primary"
                @click="paging(1)"
                icon="Search">
              搜索
            </el-button>
          </el-col>
          <el-col :span="2">
            <el-button
                type="primary"
                @click="add()"
                icon="Add">
              添加医生
            </el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-card shadow="hover">
        <el-table
            :data="page.list"
            style="width: 100%"
            stripe
            border
            v-loading="loading"
            height="calc(100vh - 280px)">

          <el-table-column
              prop="id"
              label="医生ID"
              width="100"
              align="center"
              sortable>
          </el-table-column>

          <el-table-column
              prop="name"
              label="医生姓名"
              width="120"
              align="center">
          </el-table-column>

          <el-table-column
              label="性别"
              width="80"
              align="center">
            <template v-slot="scope">
              <el-tag :type="scope.row.sex==1?'':'danger'">
                {{scope.row.sex==1?"男":"女"}}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
              prop="title"
              label="职位"
              width="150"
              align="center">
          </el-table-column>

          <el-table-column
              prop="desc"
              label="简介"
              show-overflow-tooltip>
          </el-table-column>

          <el-table-column
              label="生日"
              width="120"
              align="center">
            <template v-slot="scope">
              <el-tag type="info">
                {{formatTime(scope.row.birthday)}}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
              label="入职时间"
              width="150"
              align="center">
            <template v-slot="scope">
              <el-tag type="success">
                {{formatTime(scope.row.entryTime)}}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column
              label="头像"
              width="120"
              align="center">
            <template v-slot="scope">
              <el-image
                  style="width: 60px; height: 60px; border-radius: 50%"
                  :src="scope.row.icon"
                  :preview-src-list="[scope.row.icon]"
                  fit="cover"
                  hide-on-click-modal>
                <template #error>
                  <div class="image-error">
                    <el-icon><User /></el-icon>
                  </div>
                </template>
              </el-image>
            </template>
          </el-table-column>

          <el-table-column
              prop="clinic.name"
              label="所属门诊"
              width="180"
              align="center">
          </el-table-column>

          <el-table-column
              label="操作"
              width="180"
              fixed="right"
              align="center">
            <template v-slot="scope">
              <el-button
                  type="primary"
                  size="small"
                  @click="upd(scope.row)"
                  icon="Edit">
                编辑
              </el-button>
              <el-button
                  type="danger"
                  size="small"
                  @click="del(scope.row)"
                  icon="Delete">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-card shadow="hover">
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="paging"
            :current-page="page.pageNum"
            :page-sizes="[5, 10, 20, 50]"
            :page-size="page.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="page.total">
        </el-pagination>
      </el-card>
    </div>
    <el-dialog
        :title="form.id ? '编辑医生信息' : '新增医生信息'"
        v-model="dialogFormVisible"
        width="600px"
        center
        @closed="handleDialogClosed">

      <el-form
          :model="form"
          ref="doctorForm"
          label-position="left"
          label-width="100px"
          class="doctor-form">

        <el-form-item label="医生姓名" prop="name">
          <el-input
              v-model="form.name"
              placeholder="请输入医生姓名"
              clearable>
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select
              v-model="form.sex"
              placeholder="请选择性别"
              style="width: 100%">
            <el-option label="男" value="1"></el-option>
            <el-option label="女" value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="职位" prop="title">
          <el-input
              v-model="form.title"
              placeholder="请输入职位"
              clearable>
            <template #prefix>
              <el-icon><Briefcase /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="简介" prop="desc">
          <el-input
              v-model="form.desc"
              type="textarea"
              :rows="3"
              placeholder="请输入医生简介"
              maxlength="200"
              show-word-limit>
          </el-input>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker
                  v-model="form.birthday"
                  type="date"
                  placeholder="选择生日"
                  style="width: 100%"
                  value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职时间" prop="entryTime">
              <el-date-picker
                  v-model="form.entryTime"
                  type="date"
                  placeholder="选择入职时间"
                  style="width: 100%"
                  value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="头像" prop="icon">
          <el-upload
              class="avatar-uploader"
              action=""
              :show-file-list="false"
              :auto-upload="false"
              :on-change="handleAvatarChange">
            <img v-if="form.icon" :src="form.icon" width="200px" height="200px" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">建议尺寸：200×200像素，支持JPG/PNG格式</div>
          <el-button
              v-if="form.icon"
              type="danger"
              size="small"
              @click="removeAvatar"
              style="margin-top: 10px;">
            移除头像
          </el-button>
        </el-form-item>

        <el-form-item label="所属门诊" prop="clinicId">
          <el-select
              v-model="form.clinic.id"
              placeholder="请选择所属门诊"
              style="width: 100%"
              filterable>
            <el-option
                v-for="clinic in clinicList"
                :key="clinic.id"
                :label="clinic.name"
                :value="clinic.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogFormVisible = false" size="medium">取消</el-button>
        <el-button
            type="primary"
            @click="submitForm"
            size="medium"
            :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import axios from "axios"
import { Search, Edit, Delete, User } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
const user = ref({})
const doctorName = ref("")
const page = ref({})
const clinicList = ref([])
const pageSize = ref(10)
const loading = ref(false)
const form = ref({})
const dialogFormVisible=ref( false)
const formLabelWidth = ref('120px')
const file=ref({})

//移除头像
const removeAvatar = () => {
  form.value.icon = ''
  file.value = null
}
const add = () => {
  form.value = {
    id: null,
    name: '',
    sex: '',
    title: '',
    desc: '',
    birthday: '',
    entryTime: '',
    icon: '',
    clinic: {
      id: null
    }
  }
  dialogFormVisible.value = true

}

const paging = async (curPage) => {
  try {
    loading.value = true
    const res = await axios.get('/doctor/getAll', {
      params: {
        pageNum: curPage,
        pageSize: pageSize.value,
        hid: user.value.hid,
        name: doctorName.value
      }
    })
    page.value = res.data.data
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}
//修改逻辑
const submitForm = () => {
 if (
     form.value.name!=null &&
     form.value.sex==0 || 1 &&
     form.value.title!='' &&
     form.value.desc!='' &&
     form.value.birthday !=''&&
     form.value.entryTime!='' &&
     form.value.clinic.id!=null
 ){
   let formData = new FormData()
   formData.append('id', form.value.id?form.value.id:null)
   formData.append('name', form.value.name)
   formData.append('sex', form.value.sex)
   formData.append('title', form.value.title)
   formData.append('desc', form.value.desc)
   formData.append('birthday', form.value.birthday)
   formData.append('entryTime', form.value.entryTime)
   formData.append('icon', form.value.icon ? form.value.icon : null)
   if (file.value){
     formData.append('file', file.value)
   }
   axios.post('/doctor/save', formData).then(res => {
     if (res.data.code == 200) {
       ElMessage.success("保存成功")
       dialogFormVisible.value = false
       paging(1)
     } else {
       ElMessage.error(res.data.msg)
     }
   })
 }else {
   console.log("form.value.name="+form.value.name)
   console.log("form.value.sex="+form.value.sex)
   console.log("form.value.title="+form.value.title)
   console.log("form.value.desc="+form.value.desc)
   console.log("form.value.birthday="+form.value.birthday)
   console.log("form.value.entryTime="+form.value.entryTime)
   console.log("form.value.clinic.id="+form.value.clinic.id)
   console.log(form.value.name!=null)
   console.log(form.value.sex!='' )
   console.log(form.value.title!='' )
   console.log(form.value.desc!='' )
   console.log(form.value.birthday !='')
   console.log(form.value.entryTime!='' )
   console.log(form.value.clinic.id!=null)

   ElMessage.error("请填写必填项")
 }
}


const del = (item) => {
  axios.post('/doctor/delete?id='+item.id).then(res => {
    if (res.data.code == 200) {
      ElMessage.success("删除成功")
      paging(1)
    } else {
      ElMessage.error(res.data.msg)
    }
  })
  // 删除逻辑
}

const upd = (item) => {
  form.value = item
  dialogFormVisible.value = true
  // 修改逻辑
}
//修改对话框关闭
const handleDialogClosed = () => {
  dialogFormVisible.value = false
  paging(1)
}
//头像选择触发
const handleAvatarChange = (f) => {
  file.value= f.raw
  form.value.icon= URL.createObjectURL(f.raw)

}

const formatTime = (timestamp) => {
  if (!timestamp) return '-'
  const date = new Date(timestamp)
  return `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
}
//获取所有的门诊
const getClinic =  () => {
  axios.get('/clinic/getAll', {
    params: {
      hid: user.value.hid
    }
  }).then(res => {
    if (res.data.code == 200){
      clinicList.value = res.data.data
    }
  })
}

const handleSizeChange = (ps) => {
  pageSize.value = ps
  paging(1)
}

onMounted(() => {
  user.value = JSON.parse(sessionStorage.getItem("user"))
  paging(1)
  getClinic()
})
</script>

<style scoped>
.doctor-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-area {
  margin-bottom: 20px;
}

.table-area {
  margin-bottom: 20px;
}

.pagination-area {
  display: flex;
  justify-content: center;
}

.el-card {
  border-radius: 8px;
}

.el-table {
  border-radius: 8px;
}

.el-tag {
  margin: 2px;
}

.image-error {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
}

.el-image {
  transition: transform 0.3s;
}

.el-image:hover {
  transform: scale(1.1);
}

.el-button {
  transition: all 0.3s;
}

.el-button + .el-button {
  margin-left: 8px;
}
</style>